package org.sinuto.documentserver.service.impl;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.sinuto.documentserver.constant.Error;
import org.sinuto.documentserver.exception.DocumentServerException;
import org.sinuto.documentserver.service.FileService;
import org.sinuto.documentserver.utils.DocumentServerUtils;
import org.sinuto.documentserver.utils.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 2023/3/1 18:02 ly
 **/
@Service
public class FileServiceImpl implements FileService {
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private DocumentServerUtils documentServerUtils;
    @Value("${upload.path}")
    private String path;

    @Override
    public Map<String, Object> getFileInfo(String id) {
        return jdbcTemplate.queryForMap("SELECT a.attach_show_name, a.path FROM maintableattachfile a WHERE a.id=?", id);
    }

    @Override
    public String getFilePath(String id) {
        return jdbcTemplate.queryForObject("SELECT a.path FROM maintableattachfile a WHERE a.id=?", String.class, id);
    }

    @Override
    public List<Map<String, Object>> pagination() {
        return jdbcTemplate.queryForList("SELECT a.id, a.attach_show_name FROM maintableattachfile a WHERE a.delete_flag=?", "0");
    }

    @Override
    public void upload(MultipartFile file) throws DocumentServerException {
        if (file.isEmpty()) {
            throw DocumentServerException.build(Error.FILE_EMPTY);
        }
        String s0 = StringUtils.lowerCase(FilenameUtils.getExtension(file.getOriginalFilename()));
        documentServerUtils.assertCanView(s0);
        Date now = new Date();
        String s1 = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(now);
        String s2 = s1 + "." + s0;
        String s3 = FilenameUtils.normalize(path + s2);

        FileUtils.save(file, s3);

        jdbcTemplate.update("INSERT INTO " +
                        "maintableattachfile(id, attach_file_name, path, attach_show_name, attach_time, attach_size, delete_flag) " +
                        "VALUE(?, ?, ?, ?, ?, ?, ?)",
                s1,
                s2,
                s3,
                file.getOriginalFilename(),
                now,
                file.getSize(),
                "0"
        );
    }

}
